import { ref, isRef, unref, onMounted } from "vue";
interface gradientType {
  /** 范围 `0.0` 到 `1.0` https://www.runoob.com/tags/canvas-addcolorstop.html */
  value: number;
  /** 对应 `value` 范围的文本颜色 */
  color: string;
}
interface WatermarkOptions {
  /** 字体，默认 `15px Reggae One` */
  font?: string;
  /** 填充绘制图形的颜色，默认 `rgba(0, 0, 0, 0.15)` */
  fillStyle?: string;
  /** 宽度，默认 `250` */
  width?: number;
  /** 高度，默认 `100` */
  height?: number;
  /** 水印整体的旋转，默认 `-10` */
  rotate?: number;
  /** 水印的 `z-index`，默认 `100000` */
  zIndex?: string;
  /** 开始绘制文本的 `x` 坐标位置（相对于画布） https://www.runoob.com/jsref/met-canvas-filltext.html */
  fillTextWidth?: number;
  /** 开始绘制文本的 `y` 坐标位置（相对于画布） https://www.runoob.com/jsref/met-canvas-filltext.html */
  fillTextHeight?: number;
  /** 绘制文本渐变色，优先级高于 `fillStyle` */
  gradient?: Array<gradientType>;
  /** 创建阴影（四个参数，如下）
   *  第一个填 `shadowBlur`，`必填`，具体设置看：https://www.runoob.com/jsref/prop-canvas-shadowblur.html
   *  第二个填 `shadowColor`，`可选，默认#000000`，具体设置看：https://www.runoob.com/jsref/prop-canvas-shadowcolor.html
   *  第三个填 `shadowOffsetX`，`可选，默认0`，具体设置看：https://www.runoob.com/jsref/prop-canvas-shadowoffsetx.html
   *  第四个填 `shadowOffsetY`，`可选，默认0`，具体设置看：https://www.runoob.com/jsref/prop-canvas-shadowoffsety.html
   */
  shadowConfig?: Array<any>;
  /** 透明度，范围 `0.0`（完全透明） 到 `1.0` */
  globalAlpha?: number;
  /** 是否让水印无法删除，默认`false`，开启后在控制台操作对应的 `Elements` 也无法删除 */
  forever?: boolean;
}

interface WatermarkMethods {
  setWatermark: (text: string, options?: WatermarkOptions) => void;
  clear: () => void;
}

/**
 * useWatermark 钩子函数，用于在 Vue 组件中添加水印功能
 * @param target 要添加水印的目标元素，默认为 document.body
 * @returns WatermarkMethods 水印方法集合
 */
// 还有一种就是用canvas导出一张图片，然后通过操作dom 设置背景图 这样就能实现防止篡改
export function useWatermark(target: any = document.body): WatermarkMethods {
  const watermarkElement = ref(null);
  const watermarkSymbol = Symbol("watermark-dom");
  const t = ref(null);
  const text = ref("Your Watermark Text");

  const removeWatermark = () => {
    if (watermarkElement.value) {
      t.value.removeChild(watermarkElement.value); // 使用.value访问shallowRef的值
      watermarkElement.value = null;
    }
  };

  const createWatermark = (text, options = {}) => {
    const canvas = document.createElement("canvas");
    const ctx = canvas.getContext("2d");
    const width = options.width || 250;
    const height = options.height || 100;

    canvas.width = width;
    canvas.height = height;

    ctx.save();
    ctx.translate(width / 2, height / 2);
    ctx.rotate(((options.rotate || -10) * Math.PI) / 120);
    ctx.globalAlpha = options.globalAlpha || 1;
    ctx.font = options.font || "15px Reggae One";
    // 阴影
    if (options.shadowConfig && Array.isArray(options.shadowConfig)) {
      const [shadowBlur, shadowColor, shadowOffsetX, shadowOffsetY] =
        options.shadowConfig;
      ctx.shadowBlur = shadowBlur;
      ctx.shadowColor = shadowColor || "#000000";
      ctx.shadowOffsetX = shadowOffsetX || 0;
      ctx.shadowOffsetY = shadowOffsetY || 0;
    }
    // 渐变
    if (options.gradient && Array.isArray(options.gradient)) {
      const gradient = ctx.createLinearGradient(0, 0, width, 0);
      options.gradient.forEach(stop => {
        gradient.addColorStop(stop.value, stop.color);
      });
      ctx.fillStyle = gradient;
    } else {
      ctx.fillStyle = options.fillStyle || "rgba(0, 0, 0, 0.15)";
    }

    ctx.textAlign = "center";
    ctx.textBaseline = "middle";
    ctx.fillText(text, 0, 0);

    ctx.restore();

    return canvas.toDataURL("image/png");
  };

  const setWatermark = (texts, params = {}) => {
    text.value = texts;
    if (!t.value) return;
    const options = {
      font: "15px Reggae One",
      fillStyle: "rgba(0, 0, 0, 0.15)",
      rotate: -10,
      zIndex: "100000",
      top: "0px",
      left: "0px",
      position: "absolute",
      ...params
    };
    removeWatermark();
    t.value.style.position = t.value?.style?.position
      ? t.value.style.position
      : "relative";
    const watermarkImage = createWatermark(text.value, options);
    watermarkElement.value = document.createElement("div");
    watermarkElement.value.id = watermarkSymbol.description;
    watermarkElement.value.style.width = t.value.offsetWidth + "px"; //这里画布取得默认传进来元素的宽高
    watermarkElement.value.style.height = t.value.offsetHeight + "px";
    watermarkElement.value.style.pointerEvents = "none";
    watermarkElement.value.style.position = options.position;
    watermarkElement.value.style.top = options.top;
    watermarkElement.value.style.left = options.left;
    watermarkElement.value.style.zIndex = options.zIndex;
    watermarkElement.value.style.background = `url(${watermarkImage}) left top repeat`;
    t.value.appendChild(watermarkElement.value); // 使用shallowRef的值添加元素
  };

  const handleResize = () => {
    const { clientHeight: height, clientWidth: width } = t.value;
    setWatermark(text.value, { width, height });
  };
  //  防篡改
  // const ob = new MutationObserver(entries => {
  //      删除
  // for (const entry of entries) {
  //   for (const dom of entry.removedNodes) {
  //     if (dom === t.value) {
  //       console.log("实现控制台或者整个无法修改和删除的逻辑就是在这里，
  //       监听到后在执行一次setWatermark,这个案例里面是运行修改的");
  //       return;
  //     }
  //   }
  // }
  // });
  const init = () => {
    t.value = isRef(target) ? unref(target) : target;
    // ob.observe(t.value, {
    //   //元素变化监听
    //   childList: true,
    //   subtree: true,
    //   attributes: true
    // });
    window.addEventListener("resize", handleResize);
    handleResize();
  };
  const clearWatermark = () => {
    removeWatermark();
    window.removeEventListener("resize", handleResize);
  };
  onMounted(() => {
    init();
  });
  // onUnmounted(() => {
  //   ob.disconnect();
  // });

  return {
    setWatermark,
    clear: clearWatermark
  };
}
